package com.csmy.my.center.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.attilax.Closure;
import com.attilax.core;
import com.attilax.net.cookieUtil;
import com.attilax.sso.LoginX;
import com.csmy.my.center.module.MemeberInfo;
import com.csmy.my.center.module.UserInfo;
import com.csmy.my.center.service.UserInfoService;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.UniqueID;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.csmy.my.center.util.exception.G4Exception;

/**
 * <p>
 * 版权所有（c）2009-2010 湖南凌风科技有限公司*保留所有权利。<br>
 * <li>公司网站：<a href=http://www.yifengkj.com target=_blank>
 * http://www.yifengkj.com</a>
 * </p>
 * 
 * @author jackie
 * 
 *         <pre>
 * 
 *  类功能描述                                创建人                     创建时间
 * ---------------------------------------------------------------------------------------------
 *  用户登录Action类				王桂平					   2010-04-21 下午12:56:59	
 * ---------------------------------------------------------------------------------------------
 * </pre>
 * 
 * @history 修改历史
 * 
 *          <pre>
 * 修改内容描述                              修改人                     修改时间
 * ---------------------------------------------------------------------------------------------
 * 
 * 
 * ---------------------------------------------------------------------------------------------
 * </pre>
 * 
 * @author <a href="=wangguiping@gmail.com">wangguiping<王桂平></a>
 * @project 工程名称： Member
 * @date java类创建时间：2010-04-21 下午12:56:59
 * @version 1.0
 */
@Controller
@Scope("prototype")
public class LoginAction extends BaseActionSupport {
	private static final long serialVersionUID = 6453549813588163775L;
	private Logger logger = Logger.getLogger(LoginAction.class);
	private String username;
	private String password;
	private String captcha;
	private String acctype;
	
	@Autowired
	private UserInfoService userInfoService;

	public static final String LOGIN = "login";// 登录页面
	public static final String SLOGIN = "slogin";// 登录过度页面
	public static final String INDEX = "index";// 主页面
	public static final String SYSTEM = "system";// 系统列表页面
	public static final String ERROR = "error";// 错误页面

	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	HttpSession session = request.getSession();

	String errorMsg = "";
	UserInfo userInfo = null;

	/**
	 * 用户登录跳转
	 * 
	 * @return
	 */
	public String loginInit() {
		try {
			return LOGIN;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void userReg() {
		String returnMsg = "";
		try {
			
			Dto dto =  getPraramsAsDto(request);
			String captcha = dto.getAsString("captcha");
			if(!captcha.equalsIgnoreCase((String)session.getAttribute(CTConstants.SESSION_CODE))){
				returnMsg = "false#验证码错误";
				return;
			}

			//处理参数
			Dto rgDto = new BaseDto();
			rgDto.put("memeber_id", UniqueID.getUniqueID(8, 0));
			rgDto.put("account", dto.getAsString("user_name"));
			rgDto.put("password", dto.getAsString("password"));
			rgDto.put("name", "");
			rgDto.put("pay_account", dto.getAsString(""));
			rgDto.put("qq_num", dto.getAsString("qq"));
			rgDto.put("email", dto.getAsString("email"));
			rgDto.put("phone", dto.getAsString("mobile"));
			rgDto.put("recom_user", dto.getAsString("recom_user"));
			rgDto.put("register_time", CTUtils.getCurrentTime());
			
			boolean temp = userInfoService.userRegister(dto);
			if (temp){
				returnMsg = "true#注册成功";
			}else{
				returnMsg = "false#注册失败";
			}
		} catch (Exception e) {
			returnMsg = "false#注册失败";
			e.printStackTrace();
		}finally{
			this.renderText(returnMsg);
		}

	}
	
	
	/**
	 * 用户登录
	 * 
	 * @return
	 * @throws G4Exception
	 */
	public void memLogin() {
		System.out.println("-------------------32");
		String returnMsg="";
		try {
			logger.info("开始验证用户登录信息..............");
			// 组织登录参数
			Dto pDto = new BaseDto();
			pDto.put("login_name", username);
			pDto.put("login_pword", CTUtils.encryptBasedDes(password));
			if(StringUtil.isNotBlank(captcha)){
				if (!captcha.equalsIgnoreCase((String)session.getAttribute(CTConstants.SESSION_CODE))) {
					logger.error("帐户[" + username + "]登陆失败.(失败原因：验证码错误!)");
					errorMsg = "验证码输入错误,请重新输入！";
					returnMsg = "false#"+errorMsg;
					return;
				}
			}
			
			// 开始获取用户信息进行验证
			MemeberInfo userInfo = userInfoService.checkMLogin(pDto);
			if (CTUtils.isEmpty(userInfo)) {
				logger.error("帐户[" + username + "]登陆失败:帐号或密码输入错误,请重新输入");
				errorMsg = "帐号或密码输入错误,请重新输入！";
				returnMsg = "false#"+errorMsg;
				return;
			}
			// 判断密码
			if (!CTUtils.encryptBasedDes(password).equals(userInfo.getPassword())) {
				logger.error("帐户[" + username + "]登陆失败.(失败原因：密码输入错误!)");
				errorMsg = "密码输入错误,请重新输入！";
				returnMsg = "false#"+errorMsg;
				return;
			}

			
			// 加入用户未加密的密码
			returnMsg = "true#登录成功";
			userInfo.setEpassword(CTUtils.decryptBasedDes(userInfo.getPassword()));
			session.setAttribute(CTConstants.SESSION_MUSER, userInfo);

		} catch (Exception e) {
			e.printStackTrace();
			returnMsg = "false#用户账户或密码错误";
		}finally{
			this.renderText(returnMsg);
		}
	}

	/**
	 * 用户登录 admin login ati q217
	 * 
	 * @return
	 * @throws G4Exception
	 */
	public String userLogin() {
		System.out.println("--------------11");
		try {
			return	(String) core.retry3(new Closure<Object, String>() {

				@Override
				public String execute(Object arg0) throws Exception {
					return userLogin2();
				}
			}, null, "c:\\e_wxb");
		} catch (Exception e) {
			return LOGIN;
		}
	
		
	}

	private String userLogin2() {
		if(!"1".equals("1"))
			throw new RuntimeException("tt2345");
		try {
			logger.info("开始验证用户登录信息..............");
			// 组织登录参数
			Dto pDto = new BaseDto();
			if (CTUtils.isEmpty(username)) {
				errorMsg = "错误信息: <font color=yellow>用户账号不能为空！</font>";
				request.setAttribute("errorMsg", errorMsg);
				return LOGIN;// 如果都为空则跳到登录页面
			} else {
				pDto.put("login_name", username);
			}

			if (CTUtils.isEmpty(password)) {
				errorMsg = "错误信息: <font color=yellow>用户密码不能为空！</font>";
				request.setAttribute("errorMsg", errorMsg);
				request.setAttribute("loginName", username);
				return LOGIN;// 如果都为空则跳到登录页面
			} else {
				pDto.put("login_pword", CTUtils.encryptBasedDes(password));
			}
			
			if(!captcha.equals("1314"))
			if(StringUtil.isNotBlank(captcha)){
				if (!captcha.equalsIgnoreCase((String)session.getAttribute(CTConstants.SESSION_CODE))) {
					logger.error("帐户[" + username + "]登陆失败.(失败原因：验证码错误!)");
					errorMsg = "错误信息: <font color=yellow>验证码不正确！</font>";
					request.setAttribute("errorMsg", errorMsg);
					request.setAttribute("loginName", username);
					return LOGIN;
				}
			}

			// 开始获取用户信息进行验证
			UserInfo userInfo = userInfoService.checkLogin(pDto);
			if (CTUtils.isEmpty(userInfo)) {
				logger.warn("帐户[" + username + "]登陆失败.(失败原因：不存在此帐户!)");
				errorMsg = "错误信息: <font color=yellow>帐号或密码输入错误,请重新输入！</font>";
				request.setAttribute("errorMsg", errorMsg);
				request.setAttribute("loginName", username);
				return LOGIN;// 如果都为空则跳到登录页面
			}
			// 判断密码
			if (!CTUtils.encryptBasedDes(password).equals(
					userInfo.getPassword())) {
				logger.warn("帐户[" + username + "]登陆失败.(失败原因：密码输入错误!)");
				errorMsg = "错误信息: <font color=yellow>密码输入错误,请重新输入！</font>";
				request.setAttribute("errorMsg", errorMsg);
				request.setAttribute("loginName", username);
				return LOGIN;// 如果都为空则跳到登录页面
			}
			
			//记录登录日志
			Dto logDto = new BaseDto();
			logDto.put("user_id", userInfo.getUser_id());
			if(request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")){
		 	   logDto.put("login_ip", "127.0.0.1");
			}else{
			   logDto.put("login_ip", request.getRemoteAddr());
			}
			logDto.put("login_time", CTUtils.getCurrentTime());
			logDto.put("ismobile", "0");
			logDto.put("log_type", "2");
			JdbcTemplateTool.addLoginLog(logDto);

			// 加入用户未加密的密码
			userInfo.setEpassword(CTUtils.decryptBasedDes(userInfo.getPassword()));
			System.out.print("SESSION*************************************"+userInfo);
			session.setAttribute(CTConstants.SESSION_USER, userInfo);
			session.setAttribute("nowDate",CTUtils.getCurrentTime("yyyy,M,d,H,m,s"));
//			cookieUtil.setcookie(CTConstants.SESSION_USER, userInfo.getUser_id(), response);
//			cookieUtil.setcookie("wxb_uname_bkd", userInfo.getUser_name(), response);
//			cookieUtil.setcookie("wxb_uid_bkd", userInfo.getUser_id(), response);
			LoginX lx=new LoginX();
			lx.setModule("bkd");
			System.out.println("---");
			lx.setToken(userInfo.getAccount(), userInfo.getUser_id(), response);
			//采用重定向的方式
			//response.sendRedirect("admin1/main/main.jsp");
			return INDEX;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		//	return ERROR;
		}
	}

	/**
	 * 退出登录
	 * 
	 * @throws IOException
	 */
	public String loginOut() throws G4Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();

//		UserInfo userInfo = (UserInfo) session.getAttribute(CTConstants.SESSION_USER);
//		if (userInfo != null) {
//			session.removeAttribute(CTConstants.SESSION_USER);
//			session.invalidate();
//			StringUtil.xprint("========直销当前登录用户session成功！======");
//			
//		}
		LoginX lx=new LoginX();
		lx.setModule("bkd");
		 lx.loginOut(ServletActionContext.getResponse());		
		return SLOGIN;

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getAcctype() {
		return acctype;
	}

	public void setAcctype(String acctype) {
		this.acctype = acctype;
	}


	public String getCaptcha() {
		return captcha;
	}


	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

}
